﻿using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using System.Windows.Forms;
using ApplicationGenerator.CommonModule;
using ApplicationGenerator.CommonForms.Forms;

namespace ApplicationGenerator.CommonForms
{
    public class MethodNameTypeEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context == null)
            {
                return base.EditValue(context, provider, value);
            }

            if (context.Instance == null)
            {
                return base.EditValue(context, provider, value);
            }

            if (provider == null)
            {
                return base.EditValue(context, provider, value);
            }

            IWebServiceInvocation webServiceInvocation = context.Instance as IWebServiceInvocation;
            if (webServiceInvocation == null)
            {
                return base.EditValue(context, provider, value);
            }

            WebServiceUtility webServiceUtility = new WebServiceUtility(webServiceInvocation.WebServiceURL);
            if (!webServiceUtility.IsWebServiceUrlDefined())
            {
                if (!webServiceUtility.IsWebServiceUrlCorrectlyFormed())
                {
                    MessageBox.Show(webServiceUtility.Error);
                    return base.EditValue(context, provider, value);
                }

                try
                {
                    webServiceUtility.GenerateAssembly();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Błąd w trakcie generowania klienta do web serwisu: {0}", ex.Message));
                    return base.EditValue(context, provider, value);
                }
            }

            IWindowsFormsEditorService editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            if (editorService == null)
            {
                return base.EditValue(context, provider, value);
            }

            SelectWebServiceMethodForm dlg = new SelectWebServiceMethodForm(webServiceInvocation.WebServiceURL);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                webServiceInvocation.MappingsConfiguration = null;
                return dlg.MethodName;
            }

            return value;
        }
    }
}
